package com.houxy.controller;


import com.houxy.repository.model.bo.AdminAndExperBO;
import com.houxy.repository.model.entity.Expert;
import com.houxy.service.AdminService;
import com.houxy.service.ExpertService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class AdminLoginController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private ExpertService expertService;

    @RequestMapping("/login")
    public String login(AdminAndExperBO adminAndExperBO, int role, HttpServletRequest request, HttpSession session) {

        if (role == 1) {
            Subject subject = SecurityUtils.getSubject(); //询当前执行用户
            UsernamePasswordToken token = new UsernamePasswordToken(adminAndExperBO.getUserName(), adminAndExperBO.getPassword());
            try {
                subject.login(token);
                return "redirect:loginSuccess.jsp";
            } catch (AuthenticationException e) {
                e.printStackTrace();
                request.setAttribute("currentAdmin", adminAndExperBO);
                request.setAttribute("errInfo", "用户名密码错误");
                return "login";
            }
        } else {
            Expert expert = expertService.findByUserName(adminAndExperBO.getUserName());
            if (expert != null) {
                if (adminAndExperBO.getPassword().equals(expert.getPassword())) {
                    session.setAttribute("currentExper", expert);
                    return "front/expert/index";
                }
            }
            session.setAttribute("errInfo", "用户名密码错误");
            return "login";
        }

    }
}
